import axios from "axios"

import Vue from "vue"
import base from '../api/base'
import store from '../store/index'
import qs from "qs"
const service = axios.create({
	withCredentials: true,
	crossDomain: true,
	baseURL: base.development_url, //这个baseURL是我在main.js下配置的请求url
	timeout: 6000
})
// post请求头
service.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';

//测试header头

//401 ---认证失败
// request拦截器,在请求之前做一些处理
service.interceptors.request.use(
	config => {
		console.log(config)
		if(config.url != "/actLogin"){
			if (uni.getStorageSync('adminToken') != '') {
			    // 给请求头添加Authorization
			    config.headers["Authorization"] = uni.getStorageSync('adminToken');
			}
		}
		config.method === 'post'  ? config.data = {...config.data} : config.params = {...config.params};
		config.method === 'put' ? config.data = {...config.data} : config.params = {...config.params};
		console.log('请求拦截成功')
		return config;
	},
	error => {
		return Promise.reject(error);
	}
);

//配置成功后的拦截器
service.interceptors.response.use(res => {
	console.log("返回res:")
	console.log(res)
	if (res.data.code == 200) {
		return res.data
	} else if(res.data.code == 401){
		uni.navigateTo({
			url:'/pages/index/authLogin'
		})
		 return Promise.reject('重新认证中...');
	}
	else {
		return Promise.reject(res.data.msg);
	}
}, error => {
	console.log('err' + error)
	let { message } = error;
	if (message == "Network Error") {
	  message = "后端接口连接异常";
	}
	else if (message.includes("timeout")) {
	  message = "系统接口请求超时";
	}
	else if (message.includes("Request failed with status code")) {
	  message = "系统" + message.substr(message.length - 3) + "异常";
	}

	uni.showLoading({
		title: message
	});
	
	setTimeout(function () {
		//uni.hideLoading();
	}, 2000);
	return Promise.reject(error)
})

axios.defaults.adapter = function(config) { //自己定义个适配器，用来适配uniapp的语法
	return new Promise((resolve, reject) => {
		var settle = require('axios/lib/core/settle');
		var buildURL = require('axios/lib/helpers/buildURL');
		uni.request({
			method: config.method.toUpperCase(),
			url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
			header: config.headers,
			data: config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete: function complete(response) {
				console.log("执行完成：", response)
				if(response.errMsg == 'request:fail '){
					response = {
						data: response.data,
						status: '500',
						errMsg: '服务端请求异常',
						header: response.header,
						config: config
					};
				}else{
					response = {
						data: response.data,
						status: response.statusCode,
						errMsg: response.errMsg,
						header: response.header,
						config: config
					};
				}
				
				settle(resolve, reject, response);
			}
		})
	})
}
export default service